const express = require('express')
const conn = require('../mysql.js')
const adminRouter = express.Router()
const jwt = require("jsonwebtoken")
const { tokenNext } = require('../middleware/token.js')
const multer = require('multer')
const fs = require('fs')
const upload = multer({ dest: 'uploads/' })


// 用户模块
// 获取列表
adminRouter.get('/admin/login', (req, res) => {
    const name = req.query.name
    const password = req.query.password
    const getPoiId = req.query.poiId

    const sql = `SELECT *FROM admin_user WHERE name = ?;`;
    conn.query(sql, [name], (err, result, fields) => {
        const user = result[0];

        if (err) {
            return console.log('==err', err)
        }
        if (!user) {
            return res.send({
                code: 201,
                data: {},
                msg: '无该用户,请注册'
            })
        }
        if (user.password != password) {
            return res.send({
                code: 202,
                data: {},
                msg: '密码错误,请重新输入'
            })
        }
        if (user.poiId != getPoiId) {
            return res.send({
                code: 202,
                data: {},
                msg: '商户号错误,请重新输入'
            })
        }
        const { id, name, poiId, door_name } = user;
        const token = jwt.sign({ id, name }, "123", {
            expiresIn: 60 * 60 * 24,
            // algorithm: 'RS256'
        });
        return res.send({
            code: 200,
            data: {
                id,
                name,
                poiId,
                token,
                door_name
            },
            msg: '登录成功'
        })

    })
})
adminRouter.post('/admin/regiser', (req, res) => {
    let name = req.body.name
    let password = req.body.password

    // 判断这次注册的用户有没有被注册
    const sqlOne = `SELECT *FROM admin_user WHERE name = ?;`;
    conn.query(sqlOne, [name], (err, result, fields) => {
        if (err) {
            return console.log('==err', err)
        }
        if (result.length > 0) {
            return res.send({
                code: 200,
                data: {},
                msg: '该名称已被注册'
            })
        }
        // 创建用户
        const sqlTwo = 'insert into admin_user (name,password) values(?, ?)'
        conn.query(sqlTwo, [name, password], (err, result, fields) => {
            if (err) {
                return console.log('==err', err)
            }
            res.send({
                code: 200,
                data: {},
                msg: '注册成功'
            })
        }
        )
    })
})
adminRouter.get('/admin/user', tokenNext, (req, res) => {
    const name = req.token.name
    const sql = `SELECT * FROM admin_user where name = ?`;

    conn.query(sql, [name], (err, result, fields) => {
        const data = result[0]
        if (err) {
            return console.log('==err', err)
        }
        return res.send({
            code: 200,
            data,
            msg: '查询成功'
        })

    })
})
adminRouter.post('/admin/user/edit', tokenNext, (req, res) => {
    const name = req.token.name

    const door_name = req.body.door_name
    const isOpenState = req.body.isOpenState ? 1 : 0
    const message = req.body.message
    const phone = req.body.phone
    const address = JSON.stringify(req.body.address)
    const time = req.body.time

    const sql = `update admin_user set door_name=?, address=?, phone=?, isOpenState=?, message=?, time=?  where name = ?`;

    conn.query(sql, [door_name, address, phone, isOpenState, message, time, name], (err, result, fields) => {
        if (err) {
            return console.log('==err', err)
        }
        return res.send({
            code: 200,
            data: {},
            msg: '编辑成功'
        })

    })
})

// 笔记本
adminRouter.get('/admin/user/getTodo', (req, res) => {
    const sql = `SELECT * FROM admin_todo`;

    conn.query(sql, (err, result, fields) => {
        const data = result
        if (err) {
            return console.log('==err', err)
        }
        return res.send({
            code: 200,
            data,
            msg: '查询成功'
        })

    })
})
adminRouter.post('/admin/user/addTodo', (req, res) => {
    const text = req.body.text
    const done = req.body.done
    const editing = req.body.editing

    const sql = `insert into admin_todo (text,done,editing) values(?, ?, ?)`;

    conn.query(sql, [text, done, editing], (err, result, fields) => {
        if (err) {
            return console.log('==err', err)
        }
        if (result.affectedRows > 0) {
            return res.send({
                code: 200,
                data: {},
                msg: '添加成功'
            })
        }
    })
})
adminRouter.post('/admin/user/editTodo', (req, res) => {
    const id = req.body.id
    const done = req.body.done ? 1 : 0

    const sql = `update admin_todo set done=? where id=?`;

    conn.query(sql, [done, id], (err, result, fields) => {
        if (err) {
            return console.log('==err', err)
        }
        if (result.affectedRows > 0) {
            return res.send({
                code: 200,
                data: {},
                msg: '修改成功'
            })
        }
    })
})
adminRouter.post('/admin/user/deleteTodo', (req, res) => {
    const id = req.body.id

    const sql = `delete from admin_todo where id=?`;

    conn.query(sql, [id], (err, result, fields) => {
        if (err) {
            return console.log('==err', err)
        }
        if (result.affectedRows > 0) {
            return res.send({
                code: 200,
                data: {},
                msg: '删除成功'
            })
        }
    })
})

// 菜品中心
adminRouter.get('/admin/foodCenter/getList', (req, res) => {
    const { poiId } = req.query
    let sql = `SELECT * FROM admin_food where poiId = ? `;
    conn.query(sql, [poiId], (err, result, fields) => {
        const data = result
        if (err) {
            return console.log('==err', err)
        }
        return res.send({
            code: 200,
            data,
            msg: '查询成功'
        })
    })
})
adminRouter.post('/admin/foodCenter/searchList', (req, res) => {
    const { state, name, type, poiId, page, limit } = req.body
    let params = []

    let sql = `SELECT * FROM admin_food where poiId = ?`;
    params.push(Number(poiId));

    if (name) {
        sql += ' and name like ?';
        params.push(`%${name}%`)
    }
    if (state) {
        sql += ' and state = ?';
        params.push(state)
    }
    if (type) {
        sql += ' and type = ?';
        params.push(type)
    }
    sql += ' LIMIT ? OFFSET ?';
    params.push(parseInt(limit), (parseInt(page) - 1) * parseInt(limit));

    conn.query(sql, params, (err, result, fields) => {
        const data = result
        if (err) {
            return console.log('==err', err)
        }
        return res.send({
            code: 200,
            data,
            msg: '查询成功'
        })
    })
})
adminRouter.post('/admin/foodCenter/switch', (req, res) => {
    const { id, state } = req.body
    let sql = `update admin_food set state = ? where id = ?`;

    conn.query(sql, [Number(state), Number(id)], (err, result, fields) => {
        const data = result[0]
        if (err) {
            return console.log('==err', err)
        }
        return res.send({
            code: 200,
            data,
            msg: '修改成功'
        })
    })
})
adminRouter.post('/admin/foodCenter/deleteFood', (req, res) => {
    const { id } = req.body
    let sql = `delete FROM admin_food where id = ?`;

    conn.query(sql, [Number(id)], (err, result, fields) => {
        const data = result[0]
        if (err) {
            return console.log('==err', err)
        }
        return res.send({
            code: 200,
            data,
            msg: '删除成功'
        })
    })
})
adminRouter.post('/admin/foodCenter/editFood', (req, res) => {
    const { id, name, price, special, type, num, img } = req.body
    let sql = `update admin_food set name = ?, price = ?, special = ?, type = ?, num = ? where id = ?`;

    conn.query(sql, [name, price, special, type, Number(num), Number(id)], (err, result, fields) => {
        const data = result
        if (err) {
            return console.log('==err', err)
        }
        return res.send({
            code: 200,
            data,
            msg: '编辑成功'
        })
    })
})
adminRouter.post('/admin/foodCenter/addFood', (req, res) => {
    const timesTamp = Date.now()
    const value = parseInt(timesTamp.toString().slice(-4))

    const { poiId, name, price, special, type, num } = req.body
    let sql = `insert into admin_food (poiId, name, price, special, type, num, foodId) values(?, ?, ?, ?, ?, ?, ?)`;

    conn.query(sql, [poiId, name, price, special, type, Number(num), Number(poiId + value)], (err, result, fields) => {
        const data = result
        if (err) {
            return console.log('==err', err)
        }
        return res.send({
            code: 200,
            data,
            msg: '添加成功'
        })
    })
})

// 盲盒中心
adminRouter.get('/admin/mangCenter/getList', (req, res) => {
    const { poiId } = req.query
    let sql = `SELECT * FROM box where poiId = ? `;
    conn.query(sql, [poiId], (err, result, fields) => {
        const data = result
        if (err) {
            return console.log('==err', err)
        }
        return res.send({
            code: 200,
            data,
            msg: '查询成功'
        })
    })
})
adminRouter.post('/admin/mangCenter/searchList', (req, res) => {
    const { name, type, poiId, page, limit } = req.body
    let params = []

    let sql = `SELECT * FROM box where poiId = ?`;
    params.push(Number(poiId));

    if (name) {
        sql += ' and name like ?';
        params.push(`%${name}%`)
    }
    if (type) {
        sql += ' and type = ?';
        params.push(type)
    }
    sql += ' LIMIT ? OFFSET ?';
    params.push(parseInt(limit), (parseInt(page) - 1) * parseInt(limit));

    conn.query(sql, params, (err, result, fields) => {
        const data = result
        if (err) {
            return console.log('==err', err)
        }
        return res.send({
            code: 200,
            data,
            msg: '查询成功'
        })
    })
})
adminRouter.post('/admin/mangCenter/delete', (req, res) => {
    const { id } = req.body
    let sql = `delete FROM box where id = ?`;

    conn.query(sql, [Number(id)], (err, result, fields) => {
        const data = result[0]
        if (err) {
            return console.log('==err', err)
        }
        return res.send({
            code: 200,
            data,
            msg: '删除成功'
        })
    })
})
adminRouter.post('/admin/mangCenter/edit', (req, res) => {
    const { id, name, price, special, type, num, img, buyType } = req.body
    let sql = `update box set name = ?, price = ?, special = ?, type = ?, num = ?, buyType = ? where id = ?`;

    conn.query(sql, [name, price, special, type, Number(num), buyType, Number(id)], (err, result, fields) => {
        const data = result
        if (err) {
            return console.log('==err', err)
        }
        return res.send({
            code: 200,
            data,
            msg: '编辑成功'
        })
    })
})
adminRouter.post('/admin/mangCenter/add', (req, res) => {
    const timesTamp = Date.now()
    const time = parseInt(timesTamp.toString().slice(-4))

    const { poiId, name, price, special, type, num, img, buyType, doorName } = req.body
    let sql = `insert into box (poiId, name, price, special, type, num, foodId, buyType, doorName) values(?, ?, ?, ?, ?, ?, ?, ?, ?)`;

    conn.query(sql, [Number(poiId), name, price, special, type, Number(num), Number(poiId + time), buyType, doorName], (err, result, fields) => {
        const data = result
        if (err) {
            return console.log('==err', err)
        }
        return res.send({
            code: 200,
            data,
            msg: '添加成功'
        })
    })
})

// 消息中心
adminRouter.get('/admin/messageCenter/getList', (req, res) => {
    const { poiId } = req.query
    let sql = `SELECT * FROM message where poiId = ? `;
    conn.query(sql, [Number(poiId)], (err, result, fields) => {
        const data = result
        if (err) {
            return console.log('==err', err)
        }
        return res.send({
            code: 200,
            data,
            msg: '查询成功'
        })
    })
})

// 订单中心
adminRouter.get('/admin/orderCenter/getList', (req, res) => {
    const { poiId } = req.query
    let sql = `SELECT COUNT(*) AS count FROM orderdb where isSuccess = 1`;
    conn.query(sql, [poiId], (err, result, fields) => {
        const sucessCount = result[0].count

        let sql = `SELECT * FROM orderdb where poiId = ?`;
        conn.query(sql, [poiId], (err, result, fields) => {
            const data = result
            if (err) {
                return console.log('==err', err)
            }
            return res.send({
                code: 200,
                data,
                sucessCount,
                total: result.length,
                msg: '查询成功'
            })
        })
    })

})
adminRouter.post('/admin/orderCenter/searchList', (req, res) => {
    const { name, type, poiId, page, limit } = req.body
    let params = []

    let sql = `SELECT * FROM orderdb where poiId = ?`;
    params.push(Number(poiId));

    if (name) {
        sql += ' and name like ?';
        params.push(`%${name}%`)
    }
    if (type) {
        sql += ' and type = ?';
        params.push(type)
    }
    sql += ' LIMIT ? OFFSET ?';
    params.push(parseInt(limit), (parseInt(page) - 1) * parseInt(limit));

    conn.query(sql, params, (err, result, fields) => {
        const data = result
        if (err) {
            return console.log('==err', err)
        }
        return res.send({
            code: 200,
            data,
            msg: '查询成功'
        })
    })
})
adminRouter.post('/admin/orderCenter/switch', (req, res) => {
    const { id, type } = req.body
    let sql = `update orderdb set type = ? where id = ?`;
    if (type === 3) {
        sql = `update orderdb set type = ?, isSuccess = 1 where id = ?`
    }

    conn.query(sql, [type, Number(id)], (err, result, fields) => {
        const data = result
        if (err) {
            return console.log('==err', err)
        }
        return res.send({
            code: 200,
            data,
            msg: '订单状态编辑成功'
        })
    })
})


// 上传图片
adminRouter.post('/admin/upload', upload.array('files', 9), (req, res) => {
    const timesTamp = Date.now()
    const time = parseInt(timesTamp.toString().slice(-4))

    let sql = ''
    let value = []

    const { poiId, isWhat, stuId } = req.body
    if (req.files) {
        req.files.forEach(file => {
            const url = fs.readFileSync(file.path, { encoding: 'base64' })

            if (stuId) {
                sql = 'INSERT INTO images (poiId, isWhat, stuId, filename, path, url, foodId) VALUES (?, ?, ?, ?, ?, ?, ?)'
                value = [poiId, isWhat, stuId, file.filename, file.path, url, Number(poiId + time)]
            } else {
                sql = 'INSERT INTO images (poiId, isWhat, filename, path, url, foodId) VALUES (?, ?, ?, ?, ?, ?)'
                value = [poiId, isWhat, file.filename, file.path, url, Number(poiId + time)]
            }
            conn.query(sql, value, (err, result) => {
                if (err) throw err;
            })
        })
        return res.send(
            {
                code: 200,
                msg: '上传成功'
            }
        )
    } else {
        return res.send(
            {
                code: 200,
                msg: '上传失败'
            }
        )
    }
})
// 编辑
adminRouter.post('/admin/foodupload', upload.array('files', 9), (req, res) => {
    const { foodId } = req.body

    if (req.files) {
        req.files.forEach(file => {
            const url = fs.readFileSync(file.path, { encoding: 'base64' })
            const sql = 'update images set url = ?, filename = ?, path = ? where foodId = ?'
            conn.query(sql, [url, file.filename, file.path, foodId], (err, result) => {
                if (err) throw err;
            })
        })
        return res.send(
            {
                code: 200,
                msg: '上传成功'
            }
        )
    } else {
        return res.send(
            {
                code: 200,
                msg: '上传失败'
            }
        )
    }
})

adminRouter.post('/admin/images', (req, res) => {
    const { poiId, isWhat, foodId, stuId, isMessage } = req.body
    let sql = `SELECT * FROM images WHERE isWhat = ${isWhat}`;
    if (poiId) {
        sql += ` AND poiId = ${poiId}`
    }
    if (foodId) {
        sql += ` AND foodId = ${foodId}`
    }
    if (stuId) {
        sql += ` AND stuId = ${stuId}`
    }
    if (isMessage) {
        sql += ` AND isMessage = ${isMessage}`
    }
    conn.query(sql, (err, result) => {
        if (err) throw err;
        return res.send({
            code: 200,
            data: result,
            msg: '查看成功'
        })
    })
})

// 上传商户门店图片
adminRouter.post('/admin/shop_upload', upload.array('shopFiles', 9), (req, res) => {
    const { poiId } = req.body
    if (req.files) {
        req.files.forEach(file => {
            const url = fs.readFileSync(file.path, { encoding: 'base64' })
            const sql = 'INSERT INTO shop_images (poiId, url) VALUES (?, ?)'
            conn.query(sql, [poiId, url], (err, result) => {
                if (err) throw err;
            })
        })
        return res.send(
            {
                code: 200,
                msg: '上传成功'
            }
        )
    } else {
        return res.send(
            {
                code: 200,
                msg: '上传失败'
            }
        )
    }
})

adminRouter.get('/admin/shop_images', (req, res) => {
    let sql = 'SELECT * FROM shop_images';
    const { poiId } = req.query
    if (poiId) {
        sql += ` WHERE poiId = ${poiId} `
    }
    conn.query(sql, (err, result) => {
        if (err) throw err;
        return res.send({
            code: 200,
            data: result,
            msg: '查看成功'
        })
    })
})


//导出
module.exports = adminRouter
